package com.gss.plugin.oauth2.config.token;

import com.gss.plugin.oauth2.config.Oauth2Properties;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.web.authentication.rememberme.JdbcTokenRepositoryImpl;
import org.springframework.security.web.authentication.rememberme.PersistentTokenRepository;

import javax.annotation.Resource;
import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.ResultSet;
import java.sql.SQLException;

/**
 * @author DYang
 * @date 2023/7/6
 */
@ConditionalOnProperty(name = "stars.oauth-token.remember-me",havingValue = "true")
@Configuration
public class RememberMeToken {

    @Resource
    private Oauth2Properties oauthConfigProp;
    @Autowired
    private DataSource dataSource;

    /**
     * security 记住我功能,需要在数据库中建表持久化数据
     * @return
     */
    @Bean
    public PersistentTokenRepository persistentTokenRepository(){
        // 使用数据库存储token, 创建jdbcTokenRepository
        JdbcTokenRepositoryImpl jdbcTokenRepository = new JdbcTokenRepositoryImpl();
        jdbcTokenRepository.setDataSource(dataSource);
        if (!tokenTaleExist(dataSource)) {
            // 自动建表, 第一次启动使用,需要先判断表是否存在
            jdbcTokenRepository.setCreateTableOnStartup(true);
        }
        return jdbcTokenRepository;
    }

    /**
     * 判断存储token的表是否存在
     * @param dataSource
     * @return
     */
    private boolean tokenTaleExist(DataSource dataSource) {
        Connection conn = null;
        ResultSet rs = null;
        try {
            conn = dataSource.getConnection();
            DatabaseMetaData meta = conn.getMetaData();
            rs = meta.getTables(null, null, "persistent_logins", null);

            if (rs.next()) {
                return true;
            }
        }catch (Exception e) {
            e.printStackTrace ();
        }finally {
            if (rs != null) {
                try {
                    rs.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
            if(conn !=null) {
                try {
                    conn.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
        }
        return false;
    }

}
